package com.jz;

import com.future.util.ListNode;

/**
 * Description:
 *
 * @author weiruibai.vendor
 * Date: 2022/9/22 15:27
 */
public class JZ76 {

    /**
     * {1,2,3,3,4,4,5}
     *
     * @param args
     */
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(1);
        head.next.next = new ListNode(1);
        head.next.next.next = new ListNode(1);
        head.next.next.next.next = new ListNode(1);
        head.next.next.next.next.next = new ListNode(1);
        JZ76 jz76 = new JZ76();
        jz76.deleteDuplication(head);
    }

    /**
     * ->-1->1->2->2->2->3->3->4->5-6-6-7-7-10
     * ->-1->1->2->2->2->3->3->4->5-6-6-7-10-10
     * ->-1->1->1->1->1->1->1->4->4-4-4-4-4-4
     * <p>
     * 说明：三个指针，
     *
     * @param pHead
     * @return
     */
    public ListNode deleteDuplication(ListNode pHead) {
        if (pHead == null || pHead.next == null) {
            return pHead;
        }
        // 返回的下一个节点是答案
        ListNode newNode = new ListNode(-1);
        newNode.next = pHead;
        // 操作的节点，该节点之前的都是符合答案的
        ListNode opNode = newNode;
        // 当前节点的前一个节点
        ListNode preNode = newNode.next;
        pHead = pHead.next;
        // pHead是当前节点
        while (pHead != null) {
            if (preNode.val == pHead.val) {
                while (pHead != null && preNode.val == pHead.val) {
                    pHead = pHead.next;
                }
                if (pHead == null || pHead.next == null && preNode.val == pHead.val) {
                    // 说明preNode到末尾都是一样的值
                    opNode.next = null;
                    break;
                }
                if (pHead.next == null && preNode.val != pHead.val) {
                    // 说明末尾跟前面的不一样
                    opNode.next = pHead;
                } else {
                    preNode = pHead;
                }
            } else {
                opNode.next = preNode;
                opNode = opNode.next;
                preNode = preNode.next;
            }
            pHead = pHead.next;
        }
        return newNode.next;
    }
}
